package han.yang.service.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import han.yang.common.BaseErrorCode;
import han.yang.common.ResponseVO;
import han.yang.common.enums.DelFlagEnum;
import han.yang.common.enums.UserErrorCode;
import han.yang.common.exception.ApplicationException;
import han.yang.service.exception.LimitSizeException;
import han.yang.service.user.dao.ImUserDataEntity;
import han.yang.service.user.model.req.DeleteUserReq;
import han.yang.service.user.model.req.GetUserInfoReq;
import han.yang.service.user.model.req.ImportUserReq;
import han.yang.service.user.model.req.ModifyUserInfoReq;
import han.yang.service.user.model.resp.GetUserInfoResp;
import han.yang.service.user.model.resp.ImportUserResp;
import han.yang.service.user.service.ImUserService;
import han.yang.service.user.dao.mapper.ImUserDataMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yanghan
 * @date 2023/2/11
 */
@Service
public class ImUserServiceImpl implements ImUserService {

    @Resource
    ImUserDataMapper imUserDataMapper;

    /**
     * limitSize 批量操作的限制次数
     */
    private final int limitSize = 100;

    /**
     * 导入用户信息
     * @param req 请求信息
     * @return 返回信息
     */
    @Override
    public ResponseVO<?> importUser(ImportUserReq req) {
        if (req.getUserData().size() > limitSize){
            //TODO 返回数量过多
        }
        List<String> successId = new ArrayList<>();
        List<String> errorId = new ArrayList<>();

        req.getUserData().forEach( e -> {
            try {
                // 如果导入为其他用软件的数据，则需要将原本的appId换为自己的Id
                e.setAppId(req.getAppId()); // 填写自己真实的appId
                int insert = imUserDataMapper.insert(e);
                if (insert == 1){
                    successId.add(e.getUserId());
                }
            }catch (Exception ex){
                ex.printStackTrace();
                errorId.add(e.getUserId());
            }
        });
        ImportUserResp importUserResp = new ImportUserResp(successId, errorId);
        return ResponseVO.successResponse(importUserResp);
    }


    /**
     * 获取用户信息
     * @param req 请求用户的id
     * @return 返回信息
     */
    @Override
    public ResponseVO<GetUserInfoResp> getUserInfo(GetUserInfoReq req) {
        if (req.getUserIds().size() > limitSize){
            throw new LimitSizeException();
        }
        QueryWrapper<ImUserDataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id",req.getAppId());
        queryWrapper.in("user_id",req.getUserIds());
        queryWrapper.eq("del_flag", DelFlagEnum.NORMAL.getCode());
        // 查找出对应的用户
        List<ImUserDataEntity> imUserDataEntities = imUserDataMapper.selectList(queryWrapper);
        // 封装用户信息 key:userId value:user
        Map<String, ImUserDataEntity> collect = imUserDataEntities.stream()
                .collect(Collectors.toMap(ImUserDataEntity::getUserId, Function.identity()));
        List<String> failUser = new ArrayList<>();
        for (String uid : req.getUserIds()) {
            if(!collect.containsKey(uid)){
                failUser.add(uid);
            }
        }
        GetUserInfoResp resp = new GetUserInfoResp();
        resp.setUserDataItem(imUserDataEntities);
        resp.setFailUser(failUser);
        return ResponseVO.successResponse(resp);
    }

    /**
     * 查询单个用户信息
     * @param userId 用户的id
     * @return 返回信息
     */
    @Override
    public ResponseVO<ImUserDataEntity> getSingleUserInfo(String userId) {
        if (StringUtils.isEmpty(userId)){
            throw new ApplicationException(BaseErrorCode.PARAMETER_ERROR);
        }
        ImUserDataEntity singleUserInfo = imUserDataMapper.getSingleUserInfo(userId);
        if (singleUserInfo == null){
            throw new ApplicationException(UserErrorCode.USER_IS_NOT_EXIST);
        }
        return ResponseVO.successResponse(singleUserInfo);
    }

    /**
     * 查询单个用户信息
     * @param userId 用户的id
     * @param appId 对应的appId
     * @return 返回信息
     */
    @Override
    public ResponseVO<ImUserDataEntity> getSingleUserInfo(String userId,Integer appId) {
        QueryWrapper<ImUserDataEntity> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("app_id",appId);
        objectQueryWrapper.eq("user_id",userId);
        objectQueryWrapper.eq("del_flag", DelFlagEnum.NORMAL.getCode());

        ImUserDataEntity ImUserDataEntity = imUserDataMapper.selectOne(objectQueryWrapper);
        if(ImUserDataEntity == null){
            return ResponseVO.errorResponse(UserErrorCode.USER_IS_NOT_EXIST);
        }
        return ResponseVO.successResponse(ImUserDataEntity);
    }

    /**
     * 批量删除
     * @param req 需要批量删除的用户id
     * @return 返回信息
     */
    @Override
    public ResponseVO<?> deleteUser(DeleteUserReq req) {
//        if (req == null){
//            throw new ApplicationException(BaseErrorCode.PARAMETER_ERROR);
//        }
//        if (req.getUserId().size() > limitSize){
//            throw new LimitSizeException();
//        }
//        try {
//            imUserDataMapper.deleteUser(req.getUserId());
//        }catch (Exception e){
//            return ResponseVO.errorResponse(500,"删除用户失败");
//        }
//        return ResponseVO.successResponse();
        // 逻辑删除
        ImUserDataEntity entity = new ImUserDataEntity();
        entity.setDelFlag(DelFlagEnum.DELETE.getCode());

        List<String> errorId = new ArrayList<>();
        List<String> successId = new ArrayList<>();
        for (String userId:
                req.getUserId()) {
            QueryWrapper<ImUserDataEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("app_id",req.getAppId());
            wrapper.eq("user_id",userId);
            wrapper.eq("del_flag",DelFlagEnum.NORMAL.getCode());
            int update = 0;
            try {
                update =  imUserDataMapper.update(entity, wrapper);
                if(update > 0){
                    successId.add(userId);
                }else{
                    errorId.add(userId);
                }
            }catch (Exception e){
                errorId.add(userId);
            }
        }
        ImportUserResp resp = new ImportUserResp(successId,errorId);
        return ResponseVO.successResponse(resp);
    }

    /**
     * 修改用户信息
     * @param req 新用户信息
     * @return 返回信息
     */
    @Override
    public ResponseVO<?> modifyUserInfo(ModifyUserInfoReq req) {
        ImUserDataEntity data = getSingleUserInfo(req.getUserId()).getData();
        if (data == null){
            throw new ApplicationException(UserErrorCode.USER_IS_NOT_EXIST);
        }
        ImUserDataEntity user = new ImUserDataEntity();
        BeanUtil.copyProperties(req,user);
        try {
            imUserDataMapper.updateById(user);
        }catch (Exception e){
            return ResponseVO.errorResponse(500,"修改用户失败");
        }
        return ResponseVO.successResponse("修改用户成功");
    }
}